package com.changgou.util;

import com.changgou.file.FastDFSFile;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.core.io.ClassPathResource;

import java.io.*;
import java.net.InetSocketAddress;
import java.util.Arrays;

/**
 * @auther LiZiBa
 * @date 2020/10/14 22:31
 * @description: 文件服务工具类
 **/
public class FastDFSUtil {


    /**
     * 加载Tracker连接信息
     */
    static{
        // 加载classpath下的文件
        String filePath = new ClassPathResource("fdfs_clients.conf").getPath();
        try {
            ClientGlobal.init(filePath);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
    }


    /**
     * 文件上传
     * @param fastDFSFile
     * @throws Exception
     * @return
     */
    public static String[] upload(FastDFSFile fastDFSFile) throws Exception{

        // 通过StorageClient上传文件
        TrackerServer trackerServer = getTrackerServer();
        StorageClient storageClient = getStorageClient(trackerServer);

        NameValuePair[] meta_list = new  NameValuePair [1];
        meta_list[0] = new NameValuePair("拍摄地点", "北京");

        /**
         * @param 文件字节流
         * @param 文件扩展名
         * @param 扩展信息
         */

        String[] uploads = storageClient.upload_file(fastDFSFile.getContent(), fastDFSFile.getExt(), meta_list);

        return uploads;
    }


    /**
     * 获取文件信息
     * @param group_name        组名  group1
     * @param remote_filename   文件的存储路径  M00/00/00/wKjThF-KXU6AFFm2ADsnNuBgr1c715.png
     * @return
     * @throws Exception
     */
    public static FileInfo getFile(String group_name,String remote_filename) throws Exception{

        TrackerServer trackerServer = getTrackerServer();
        StorageClient storageClient = getStorageClient(trackerServer);
        /**
         *  * @return 2 elements string array if success:<br>
         *    * <ul><li>results[0]: the group name to store the file</li></ul>
         *    * <ul><li>results[1]: the new created filename</li></ul>
         */
        FileInfo file_info = storageClient.get_file_info(group_name, remote_filename);
        return file_info;
    }


    /**
     * 文件下载
     * @param group_name        组名  group1
     * @param remote_filename   文件的存储路径  M00/00/00/wKjThF-KXU6AFFm2ADsnNuBgr1c715.png
     * @return
     * @throws Exception
     */
    public static InputStream downloadFile(String group_name, String remote_filename) throws Exception {

        TrackerServer trackerServer = getTrackerServer();
        StorageClient storageClient = getStorageClient(trackerServer);
        byte[] bytes = storageClient.download_file(group_name, remote_filename);
        InputStream byteArrayInputStream = new ByteArrayInputStream(bytes);

        return byteArrayInputStream;
    }


    /**
     * 文件删除
     * @param group_name        组名  group1
     * @param remote_filename   文件的存储路径  M00/00/00/wKjThF-KXU6AFFm2ADsnNuBgr1c715.png
     * @return 受影响行数  删除一条返回为0
     * @throws Exception
     */
    public static int deleteFile(String group_name, String remote_filename) throws Exception {

        TrackerServer trackerServer = getTrackerServer();
        StorageClient storageClient = getStorageClient(trackerServer);
        int i = storageClient.delete_file(group_name, remote_filename);

        return i;
    }


    /**
     * 获取StorageServer信息
     * @return
     * @throws Exception
     */
    public static StorageServer getStorages() throws Exception{

        // 创建tracker客户端，用于访问tracker
        TrackerClient trackerClient = new TrackerClient();
        // 连接trackerserver
        TrackerServer trackerServer = trackerClient.getConnection();
        //
        StorageServer storeStorage = trackerClient.getStoreStorage(trackerServer);

        return storeStorage;
    }

    /**
     * 获取StorageServer IP和端口
     * @param group_name
     * @param remote_filename
     * @return
     * @throws Exception
     */
    public static ServerInfo[] getServerInfo(String group_name, String remote_filename) throws Exception{

        // 创建tracker客户端，用于访问tracker
        TrackerClient trackerClient = new TrackerClient();
        // 连接trackerserver
        TrackerServer trackerServer = trackerClient.getConnection();
        // 获取StorageServer
        ServerInfo[] fetchStorage = trackerClient.getFetchStorages(trackerServer, group_name, remote_filename);

        return fetchStorage;
    }

    /**
     * 获取Tracker 信息
     * @return
     * @throws Exception
     */
    public static String getTrackerInfo() throws Exception {

        TrackerServer trackerServer = getTrackerServer();
        InetSocketAddress inetSocketAddress = trackerServer.getInetSocketAddress();
        int tracker_http_port = ClientGlobal.getG_tracker_http_port();

        return "http://" + inetSocketAddress + ":" + tracker_http_port;
    }


    /**
     * 获取 TrackerServer
     * @return
     * @throws Exception
     */
    private static TrackerServer getTrackerServer() throws Exception{

        // 创建tracker客户端，用于访问tracker
        TrackerClient trackerClient = new TrackerClient();
        // 连接trackerserver
        TrackerServer trackerServer = trackerClient.getConnection();


        return  trackerServer;
    }

    /**
     * 获取StorageClient
     * @param trackerServer
     * @return
     * @throws Exception
     */
    private static StorageClient getStorageClient(TrackerServer trackerServer) throws Exception{
        // 创建storageClient，用于连接
        StorageClient storageClient = new StorageClient(trackerServer, null);
        return  storageClient;
    }



//    public static void main(String[] args) throws Exception {

    // 附件下载测试
//        InputStream in = downloadFile("group1", "M00/00/00/wKjThF-KXU6AFFm2ADsnNuBgr1c715.png");
//        byte [] buffer = new byte[1024];
//        OutputStream os = new FileOutputStream("D:/1.png");
//        while(in.read(buffer) != -1) {
//            os.write(buffer);
//        }
//        os.flush();;
//        os.close();
//        in.close();

    // 附件删除测试
//        int i = deleteFile("group1", "M00/00/00/wKjThF-Kd0uAa2DkADsnNuBgr1c076.png");
//        System.out.println(i);

//        ServerInfo[] group1s = getServerInfo("group1", "M00/00/00/wKjThF-KWoSAShNjADsnNuBgr1c594.png");
//        Arrays.asList(group1s).forEach(x -> {
//            System.out.println(x.getIpAddr());
//            System.out.println(x.getPort());
//        });
//    }
}
